<template>
  <t-dialog :visible.sync="visible" header="编 辑" @confirm="handleConfirm" @cancel="handleCancel" @close="handleCancel">
    <t-form ref="formRef" :data="form" :rules="rules">

      <t-form-item label="姓 名" name="name" required>
        <t-input v-model="form.name" placeholder="请输入" clearable />
      </t-form-item>
      <t-form-item label="手 机" name="mobile">
        <t-input v-model="form.mobile" placeholder="请输入" clearable />
      </t-form-item>

      <t-form-item label="邮 箱" name="email">
        <t-input v-model="form.email" placeholder="请输入" clearable />
      </t-form-item>

      <t-form-item label="部 门" name="deptId">
        <t-cascader v-model="form.deptIds" :options="options" clearable placeholder="请选择" />
      </t-form-item>
      <t-form-item label="岗 位" name="postIds">
        <t-select v-model="form.postIds" placeholder="请选择" clearable>
          <t-option v-for="(item, index) in postOptions" :key="index" :value="item.value" :label="item.label" />
        </t-select>
      </t-form-item>

      <t-form-item label="备 注" name="remark">
        <t-textarea v-model="form.remark" placeholder="请输入" clearable />
      </t-form-item>
    </t-form>
  </t-dialog>
</template>
<script setup lang="ts">
import { getById, update } from '@/api/userCenter/dept/staff';
import { FormRules, MessagePlugin, } from 'tdesign-vue-next';
import { defineExpose, ref } from 'vue';
const visible = ref?.(false);
const loading = ref?.(false);
const formRef = ref?.(null);
const form = ref?.({
  id: '',
  name: '',
  mobile: '',
  email: '',
  deptIds: '',
  postIds: '',
  remark: '',
  title: '',
  content: ''
});
// 表单验证规则
const rules: FormRules = {
  name: [{ required: true, message: '请输入姓名', type: 'error' }],
};
const options = ref?.([]);
const postOptions = ref?.([]);
const handleConfirm = async () => {
  if (!formRef) return;
  // 先进行表单验证
  const valid = await formRef?.value?.validate?.();
  if (valid !== true) {
    return;
  }
  loading.value = true;
  try {
    await update(form.value);
    MessagePlugin?.success?.(`操作成功`);
    visible.value = false;
    emit?.('success');
    formRef?.value?.reset();

  } catch (t) {
  } finally {
    loading.value = false;
  }
};
const handleCancel = () => {
  visible.value = false;
};
const openDialog = async (id?: string) => {
  visible.value = true;
  if (id) {
    loading.value = true;
    form.value.id = id;

    const val = await getById(id);
    if (val && Object?.keys?.(val)?.length) {
      form.value = { ...form?.value, ...val, }
    }
    loading.value = false;
  }
};
defineExpose({
  openDialog,
});
const emit = defineEmits(['success']);
</script>
<style lang="less" scoped>
/* 可以在这里添加自定义样式 */
</style>
